import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条样式
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout'

const _import = require('./router/_import') // 获取组件

NProgress.configure({
	showSpinner: false
}) // 进度条配置

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

// 用来获取后台拿到的路由
var asyncRoutes

router.beforeEach(async(to, from, next) => {
	// 启动进度条
	NProgress.start()
	// 设置页面标题
	document.title = getPageTitle(to.meta.title)
	if(getToken()) {
		if(to.path === '/login') {
			// 已登录 + 访问login页面 -> 跳转首页
			next({
				path: '/'
			})
		} else {
			// 是否获取权限 determine whether the user has obtained his permission roles through getInfo
			const hasRoles = store.getters.roles && store.getters.roles.length > 0
			if(hasRoles) {
				next()
			} else {
				try {
					// 获取角色路由菜单标识, 必须是数组: ['index'] or ,['index','login']
					const {perms} = await store.dispatch('user/getInfo');
					// 存储并获取路由数据
					const accessRoutes = await store.dispatch('permission/generateRoutes', {'flags': perms})
					// dynamically add accessible routes
					router.addRoutes(accessRoutes)
					// hack method to ensure that addRoutes is complete
					// set the replace: true, so the navigation will not leave a history record
					next({ ...to,replace: true})
				} catch(error) {
					// remove token and go to login page to re-login
					await store.dispatch('user/resetToken')
					Message.error(error || 'Has Error')
					next(`/login`)
					NProgress.done()
				}
			}
		}
	} else {
		/* has no token*/
		if(whiteList.indexOf(to.path) !== -1) {
			// in the free login whitelist, go directly
			next()
		} else {
			// other pages that do not have permission to access are redirected to the login page.
			next(`/login?redirect=${to.path}`)
			NProgress.done()
		}
	}
})

router.afterEach(() => {
	// 结束进度条
	NProgress.done()
})